package com.block.source.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.SourceCountDTO;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.ISourceDataCountInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.vo.ResponseVo;
import com.block.datapush.model.result.SpePushResut;
import com.block.datapush.special.enums.OrderStatusEnum;
import com.block.datapush.special.service.ISpecialCostomInfoService;
import com.block.db.entity.SourceBaseInfo;
import com.block.db.entity.SourceMemberDataInfoTemp;
import com.block.db.entity.SourcePushResultInfo;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.dto.SourceMatchResultDTO;
import com.block.source.model.dto.SourceRegisterResultDTO;
import com.block.source.service.ISourceBaseInfoService;
import com.block.source.service.ISourceMatchHandleService;
import com.block.source.service.ISourceMemberDataInfoService;
import com.block.source.service.ISourcePushResultInfoService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * <p>
 * 线索推送结果表 服务实现类
 * </p>
 *
 * @author
 * @since 2023-12-28
 */
@Service
public class SourcePushResultInfoServiceImpl extends ServiceImpl<SourcePushResultInfoMapper, SourcePushResultInfo> implements ISourcePushResultInfoService {

    private static final Logger log = LogFactory.getSourceLog();

    @Autowired
    ISourceMatchHandleService sourceMatchHandleService;
    @Autowired
    ISourceMemberDataInfoService sourceMemberDataInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    ISourceBaseInfoService sourceBaseInfoService;
    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    ISpecialCostomInfoService specialCostomInfoService;
    @Autowired
    ISourceDataCountInfoService sourceDataCountInfoService;

    /**
     * 撞库完成之后，保存撞库结果
     *
     * @param memberDataInfoTemp
     * @param resultDTO
     * @return
     */
    @Override
    public SourcePushResultInfo savePushResultInfo(SourceMemberDataInfoTemp memberDataInfoTemp, SourceMatchResultDTO resultDTO, SourceBaseInfo sourceBaseInfo) {

        SourcePushResultInfo newEntity = new SourcePushResultInfo();
        newEntity.setDateInfo(LocalDate.now().toString());
        newEntity.setDataId(memberDataInfoTemp.getId());
        newEntity.setChannelCode(memberDataInfoTemp.getChannelCode());
        newEntity.setChannelName(memberDataInfoTemp.getChannelName());
        newEntity.setOutOrderNo(memberDataInfoTemp.getOutOrderNo());
        newEntity.setBaseAmount(sourceBaseInfo.getPriceAmount());
        newEntity.setOrderNo(resultDTO.getOrderNo());
        newEntity.setInfoId(resultDTO.getInfoId());
        newEntity.setInfoName(resultDTO.getInfoName());
        newEntity.setInfoType(resultDTO.getInfoType());
        newEntity.setTaskId(resultDTO.getTaskId());
        newEntity.setPriceAmount(resultDTO.getPriceAmount());
        newEntity.setStatus(OrderStatusEnum.INIT.getValue());
        newEntity.setMessage("待推送");
        newEntity.setSettleStatus(OrderStatusEnum.INIT.getValue());

        boolean save = this.save(newEntity);
        if (save) {
            return this.getById(newEntity.getId());
        }
        return null;
    }

    /**
     * 推送给商户逻辑
     * 是否推送成功/是否结算/
     * @param pushResultInfo
     */
    @Override
    public SourceRegisterResultDTO handlePushToMerchant(SourcePushResultInfo pushResultInfo) {

        SourceRegisterResultDTO registerResultDTO = new SourceRegisterResultDTO();
        registerResultDTO.setSuccess(false);
        try {

            // 授权点击统计
            SourceCountDTO sourceCountDTO = new SourceCountDTO(pushResultInfo.getChannelCode(), pushResultInfo.getChannelName());
            sourceCountDTO.setClickApproveNumber(1);

            SourcePushResultInfo updateResult = new SourcePushResultInfo();
            updateResult.setId(pushResultInfo.getId());

            // 2023/12/28 进行数据推送
            SpePushResut spePushResut = specialCostomInfoService.registerUser(pushResultInfo.getOrderNo());
            log.info("【机构点击推送】推送结束【spePushResut】{}", JSON.toJSONString(spePushResut));

            // api 和 crm 进行更新推送结果
            if (!spePushResut.isPushSuccess()) {
                // 推送失败
                updateResult.setStatus(OrderStatusEnum.FAILED.getValue());
                updateResult.setSettleStatus(OrderStatusEnum.FAILED.getValue());
                updateResult.setMessage(spePushResut.getMessage());

                registerResultDTO.setSuccess(false);
            }else{
                // 推送成功，进行数据统计
                sourceCountDTO.setApproveSuccessNumber(1);

                updateResult.setStatus(OrderStatusEnum.SUCCESS.getValue());
                updateResult.setSettleStatus(OrderStatusEnum.SUCCESS.getValue());
                registerResultDTO.setSuccess(true);
            }

            sourceDataCountInfoService.saveSourceCountInfo(sourceCountDTO);

            this.updateById(updateResult);
            return registerResultDTO;

        } catch (Exception exception) {
            log.error("resultNo:{}, 线索推送异常:{}", pushResultInfo.getId(), exception);
        }
        return registerResultDTO;
    }

    @Override
    public ResponseVo manualApproveToPush(String orderNo) {

        SourcePushResultInfo pushResultInfo = this.getById(orderNo);

        SourceRegisterResultDTO sourceRegisterResultDTO = this.handlePushToMerchant(pushResultInfo);
        boolean success = sourceRegisterResultDTO.isSuccess();
        if (success){
            return new ResponseVo(AppRspCodeConstant.SUCCESS);
        }
        return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION);
    }

}
